<?php

namespace app\admin\model\scanwork;

use think\Model;

class MaterialSupplier extends Model
{
    // 表名
    protected $name = 'scanwork_material_supplier';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'price_text',
        'status_text',
        'is_preferred_text',
        'quality_rating_text',
        'service_rating_text'
    ];

    /**
     * 价格文本
     */
    public function getPriceTextAttr($value, $data)
    {
        return '¥' . number_format($data['price'], 4);
    }

    /**
     * 状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = isset($data['status']) ? $data['status'] : 1;
        $text = $status == 1 ? '正常' : '停止合作';
        $color = $status == 1 ? 'success' : 'danger';
        
        return '<span class="label label-' . $color . '">' . $text . '</span>';
    }

    /**
     * 是否优先供应商文本
     */
    public function getIsPreferredTextAttr($value, $data)
    {
        $isPreferred = isset($data['is_preferred']) ? $data['is_preferred'] : 0;
        $text = $isPreferred == 1 ? '是' : '否';
        $color = $isPreferred == 1 ? 'success' : 'default';
        
        return '<span class="label label-' . $color . '">' . $text . '</span>';
    }

    /**
     * 质量评分文本
     */
    public function getQualityRatingTextAttr($value, $data)
    {
        $rating = isset($data['quality_rating']) ? $data['quality_rating'] : 5;
        $stars = str_repeat('★', $rating) . str_repeat('☆', 5 - $rating);
        
        return '<span class="text-warning">' . $stars . '</span>';
    }

    /**
     * 服务评分文本
     */
    public function getServiceRatingTextAttr($value, $data)
    {
        $rating = isset($data['service_rating']) ? $data['service_rating'] : 5;
        $stars = str_repeat('★', $rating) . str_repeat('☆', 5 - $rating);
        
        return '<span class="text-warning">' . $stars . '</span>';
    }

    /**
     * 关联物料
     */
    public function material()
    {
        return $this->belongsTo('Material', 'material_id', 'id');
    }

    /**
     * 关联供应商
     */
    public function supplier()
    {
        return $this->belongsTo('Supplier', 'supplier_id', 'id');
    }

    /**
     * 检查价格是否有效
     */
    public function isPriceValid()
    {
        $now = time();
        $validFrom = $this->price_valid_from ?: 0;
        $validTo = $this->price_valid_to ?: PHP_INT_MAX;
        
        return $now >= $validFrom && $now <= $validTo;
    }

    /**
     * 获取有效价格
     */
    public function getValidPrice()
    {
        if ($this->isPriceValid()) {
            return $this->price;
        }
        
        return null;
    }
}